<template>
  <div>
    <ElRow style="margin-bottom: 16px;">
      <el-button type="primary" @click="handleAddUser" v-if="hasPerms('admin:account:create')">新增</el-button>
    </ElRow>
    <ReTable :data="usersList" :columns="columns" :pagination="pagination" @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <template #action="{ row }">
        <ElRow justify="center" align="middle">
          <ElCol :span="6" v-if="hasPerms('admin:account:edit')">
            <ElButton link type="primary" @click="handleEditUser(row)">
              编辑
            </ElButton>
          </ElCol>
          <ElCol :span="6" v-if="hasPerms('admin:account:status')">
            <ElSwitch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1"
              :inactive-value="0" @change="handleStatusChange(row)">
            </ElSwitch>
          </ElCol>
        </ElRow>
      </template>
    </ReTable>
    <ElDialog v-model="dialogVisible" :title="dialogTitle" width="480" :close-on-click-modal="false">
      <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
        <ElFormItem label="账号" prop="account">
          <ElInput v-model="ruleForm.account" autocomplete="off" placeholder="请输入账号" />
        </ElFormItem>
        <ElFormItem label="名称" prop="name">
          <ElInput v-model="ruleForm.name" autocomplete="off" placeholder="请输入名称" />
        </ElFormItem>
        <ElFormItem label="密码" prop="password">
          <ElInput v-model="ruleForm.password" autocomplete="off" clearable placeholder="请输入密码" />
        </ElFormItem>
        <ElFormItem label="角色" prop="roleId">
          <ElSelect v-model="ruleForm.roleId" placeholder="请选择角色">
            <ElOption v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.roleId" />
          </ElSelect>
        </ElFormItem>
        <ElRow justify="end">
          <ElCol :span="4">
            <ElButton @click="dialogVisible = false">取消</ElButton>
          </ElCol>
          <ElCol :span="4">
            <ElButton type="primary" @click="submitForm(ruleFormRef)">确定</ElButton>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { queryAccountList, createAccount, updateAccount, queryAllRoleList, updateAccountStatus } from '@/api/account';
import ReTable from '@/components/ReTable';
import { hasPerms } from '@/utils/auth';
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';
import { ref } from 'vue';

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "AccountManage"
});

// 后台账号管理列表数据
const usersList = ref([])

// 新增账号对话框
const dialogVisible = ref(false)
// 新增账号对话框标题
const dialogTitle = ref('新增账号')
// 新增账号表单
const ruleFormRef = ref()
const ruleForm = ref({
  account: '',
  name: '',
  password: '',
  roleId: ''
})
// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
// 列配置
const columns = [
  {
    prop: 'id',
    label: 'id',
    align: 'center'
  },
  {
    prop: 'name',
    label: '姓名',
    align: 'center'
  },
  {
    prop: 'account',
    label: '账号',
    align: 'center'
  },
  {
    prop: 'roleName',
    label: '角色',
    align: 'center'
  },
  {
    prop: 'gmtCreate',
    label: '创建时间',
    align: 'center'
  },
  {
    prop: 'createBy',
    label: '创建人',
    align: 'center'
  },
  {
    prop: 'action',
    label: '操作',
    slotName: 'action',
  }
]

// 角色列表
const roleList = ref([])

// 新增账号表单校验
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  password: [
    { min: 8, message: '密码长度不能小于8位', trigger: 'change' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback()
          return
        }
        console.log(value)
        // 校验密码必须包含字母、数字、特殊符号中的任意两种且长度大于8位
        const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/;
        if (!reg.test(value)) {
          callback(new Error('密码必须包含大写字母、数字、特殊字符且至少8位'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ]
}

// 新增账号
const handleAddUser = () => {
  dialogVisible.value = true
}

// 提交表单
const submitForm = (formEl: any) => {
  if (!formEl) return
  formEl.validate((valid: any) => {
    if (valid) {
      console.log('submit!', ruleForm.value)
      if (dialogTitle.value === '新增账号') {
        createAccount(ruleForm.value).then(res => {
          if (res.code === 200) {
            ElMessage.success({
              message: '新增成功',
            })
            dialogVisible.value = false
            ruleForm.value = {
              account: '',
              name: '',
              password: '',
              roleId: ''
            }
            getAccountList()
          }
        })
      } else {
        updateAccount(ruleForm.value).then(res => {
          if (res.code === 200) {
            ElMessage.success({
              message: '修改成功',
            })
            dialogVisible.value = false
            ruleForm.value = {
              account: '',
              name: '',
              password: '',
              roleId: ''
            }
            getAccountList()
          }
        })
      }

    } else {
      return false
    }
  })
}

// 查询账号列表
const getAccountList = () => {
  queryAccountList({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize
  }).then(res => {
    if (res.code === 200) {
      usersList.value = res.data.records
      pagination.value.total = res.data.total
    }
  })
}

// 编辑账号
const handleEditUser = (row: any) => {
  ruleForm.value = {
    ...row,
    roleId: parseInt(row.roleId)
  }
  dialogTitle.value = '编辑账号'
  dialogVisible.value = true
}

// 修改账号状态
const handleStatusChange = (row: any) => {
  updateAccountStatus(row.id, row.status).then(res => {
    if (res.code === 200) {
      ElMessage.success({
        message: '修改成功',
      })
      getAccountList()
    }
  })
}


const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  getAccountList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  getAccountList()
}

onMounted(() => {
  queryAllRoleList().then(res => {
    if (res.code === 200) {
      roleList.value = res.data
    }
  })
  getAccountList()
})

</script>